/*
 * This file is part of Cadmium.
 * Copyright (C) 2007-2010 Xavier Clerc.
 *
 * Cadmium is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Cadmium is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package fr.x9c.cadmium.primitives.stdlib;

import java.io.IOException;
import java.io.InterruptedIOException;

import fr.x9c.cadmium.kernel.Block;
import fr.x9c.cadmium.kernel.Channel;
import fr.x9c.cadmium.kernel.CodeRunner;
import fr.x9c.cadmium.kernel.Fail;
import fr.x9c.cadmium.kernel.FalseExit;
import fr.x9c.cadmium.kernel.Primitive;
import fr.x9c.cadmium.kernel.PrimitiveProvider;
import fr.x9c.cadmium.kernel.Value;

/**
 * Implements all primitives from 'extern.c'.
 *
 * @author <a href="mailto:cadmium@x9c.fr">Xavier Clerc</a>
 * @version 1.0
 * @since 1.0
 */
@PrimitiveProvider
public final class Extern {

    /**
     * No instance of this class.
     */
    private Extern() {
    } // end empty constructor

    /**
     * Outputs a value to an ouput channel.
     * @param ctxt context
     * @param channel output channel
     * @param v value to output
     * @param flags flag list controlling output
     * @return <i>unit</i>
     * @throws Fail.Exception if value is not serializable
     * @throws Fail.Exception if an i/o error occurs
     */
    @Primitive
    public static Value caml_output_value(final CodeRunner ctxt,
                                          final Value channel,
                                          final Value v,
                                          final Value flags)
        throws Fail.Exception, FalseExit {
        try {
            final byte[] b =
                fr.x9c.cadmium.kernel.Extern.externValue(ctxt.getContext(),
                                                         v,
                                                         flags);
            ((Channel) channel.asBlock().asCustom()).asDataOutput().write(b);
        } catch (final InterruptedIOException iioe) {
            final FalseExit fe =
                FalseExit.createFromContext(ctxt.getContext());
            fe.fillInStackTrace();
            throw fe;
        } catch (final IOException ioe) {
            Sys.sysError(null, ioe.toString());
        } // end try/catch
        return Value.UNIT;
    } // end method 'caml_output_value(CodeRunner, Value, Value, Value)'

    /**
     * Outputs a value to a string.
     * @param ctxt context
     * @param v value to output
     * @param flags flag list controlling output
     * @return string containing bytes representing <tt>v</tt>
     * @throws Fail.Exception if value is not serializable
     * @throws Fail.Exception if an i/o error occurs
     */
    @Primitive
    public static Value caml_output_value_to_string(final CodeRunner ctxt,
                                                    final Value v,
                                                    final Value flags)
        throws Fail.Exception, FalseExit {
        try {
            final byte[] b =
                fr.x9c.cadmium.kernel.Extern.externValue(ctxt.getContext(),
                                                         v,
                                                         flags);
            return Value.createFromBlock(Block.createString(b));
        } catch (final InterruptedIOException iioe) {
            final FalseExit fe =
                FalseExit.createFromContext(ctxt.getContext());
            fe.fillInStackTrace();
            throw fe;
        } catch (final IOException ioe) {
            Sys.sysError(null, "error during marshalling");
            return Value.UNIT; // never reached
        } // end try/catch
    } // end method 'caml_output_value_to_string(CodeRunner, Value, Value)'

    /**
     * Outputs a value to a buffer/string.
     * @param ctxt context
     * @param buff output buffer/string
     * @param offset destination offset in <tt>buff</tt>
     * @param len buffer length
     * @param v value to output
     * @param flags flag list controlling output
     * @return the number of bytes actually written
     * @throws Fail.Exception if value is not serializable
     * @throws Fail.Exception if an i/o error occurs
     */
    @Primitive
    public static Value caml_output_value_to_buffer(final CodeRunner ctxt,
                                                    final Value buff,
                                                    final Value offset,
                                                    final Value len,
                                                    final Value v,
                                                    final Value flags)
        throws Fail.Exception, FalseExit {
        try {
            final byte[] b = fr.x9c.cadmium.kernel.Extern.externValue(ctxt.getContext(),
                                                                      v,
                                                                      flags);
            final int ofs = offset.asLong();
            final int sz = Math.min(b.length, len.asLong());
            System.arraycopy(b, 0, buff.asBlock().getBytes(), ofs, sz);
            return Value.createFromLong(sz);
        } catch (final InterruptedIOException iioe) {
            final FalseExit fe =
                FalseExit.createFromContext(ctxt.getContext());
            fe.fillInStackTrace();
            throw fe;
        } catch (final IOException ioe) {
            Sys.sysError(null, "error during marshalling");
            return Value.UNIT; // never reached
        } // end try/catch
    } // end method 'caml_output_value_to_buffer(CodeRunner, Value, Value, ...)'

} // end class 'Extern'
